package com.company.ljh.easy;

import com.company.ljh.utils.ListNode;

/**
 * @description:
 * @projectName:leet_code
 * @see:com.company.ljh.easy
 * @author:ljh
 * @createTime:2022/3/24 16:03
 * @version:1.0
 */
public class 相交链表 {
    /**
     * 双指针法
     * 思路：寻找两个链表的长度差，然后快慢指针
     *
     * @param headA
     * @param headB
     * @return
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode node1 = headA;
        ListNode node2 = headB;
        while (node1 != null && node2 != null){
            node1 = node1.next;
            node2 = node2.next;
        }
        if (node1 == null){
            int i = 0;
            while (node2 != null){
                node2 = node2.next;
                i++;
            }
            node1 = headA;
            node2 = headB;
            while (i-- > 0){
                node2 = node2.next;
            }
            while (node1 != node2){
                node1 = node1.next;
                node2 = node2.next;
            }
            return node1;
        }
        if (node2 == null){
            int i = 0;
            while (node1 != null){
                node1 = node1.next;
                i++;
            }
            node1 = headA;
            node2 = headB;
            while (i-- > 0){
                node1 = node1.next;
            }
            while (node1 != node2){
                node1 = node1.next;
                node2 = node2.next;
            }
            return node1;
        }
        return null;
    }

}
